import { getUserInfoApi } from '@/api/user'
import { store } from '@/store'
import { UserInfo } from '@/api/user/types'
export const useUserStore = defineStore('user', () => {
  const user = ref<UserInfo>({
    roles: [],
    perms: [],
  })
  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfoApi()
        .then(({ data }) => {
          if (!data) {
            reject('Verification failed, please Login again.')
            return
          }
          if (!data.roles || data.roles.length <= 0) {
            reject('getUserInfo: roles must be a non-null array!')
            return
          }
          Object.assign(user.value, { ...data })
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // remove token
  function resetToken() {
    console.log('resetToken')
    return new Promise<void>((resolve) => {
      localStorage.setItem('accessToken', '')
      resolve()
    })
  }
  return {
    user,
    getUserInfo,
    resetToken,
  }
})

// 非setup
export function useUserStoreHook() {
  return useUserStore(store)
}
